package com.example.ceramics.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.ceramics.R;
import com.example.ceramics.database.dao.IUserDao;
import com.example.ceramics.database.dao.UserDaoImpl;
import com.example.ceramics.entity.UserEntity;
import com.example.ceramics.util.RealPathFromUriUtils;
import com.example.ceramics.util.StringUtils;
import com.example.ceramics.view.CircleTransform;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.io.FileNotFoundException;

public class UserActivity extends BaseActivity {

    private EditText etName;
    private EditText etPhone;
    private EditText etEmail;
    private String name;
    private String phone;
    private String email;
    private String path = null;
    private Uri uri;
    private String uriString;
    private ImageView ivAvatar;

    private IUserDao userDao;

    @Override
    protected int initLayout() {
        return R.layout.activity_user;
    }

    @Override
    protected void initView() {
        etName = findViewById(R.id.et_name);
        etPhone = findViewById(R.id.et_phone);
        etEmail = findViewById(R.id.et_email);
        ivAvatar = findViewById(R.id.iv_avatar);
    }

    @Override
    protected void initData() {
        userDao = new UserDaoImpl(mContext);
        UserEntity user = userDao.getUser(getStringFromSp("account"));
        etName.setText(user.getNickname());
        etPhone.setText(user.getPhone());
        etEmail.setText(user.getEmail());
//        ivAvatar.setImageResource(user.getImg());
        uriString = user.getImg();
        if (!StringUtils.isEmpty(uriString)) {
            uri = Uri.parse(uriString);
            Picasso.with(this)
                    .load(uri)
                    .transform(new CircleTransform())
                    .placeholder(R.mipmap.logo)
                    .error(R.mipmap.logo)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .config(Bitmap.Config.RGB_565)
                    .into(ivAvatar);
        }

//        SharedPreferences spFile = getSharedPreferences("user", Context.MODE_PRIVATE);
//        name = spFile.getString("name", null);
//        phone = spFile.getString("phone", null);
//        email = spFile.getString("email", null);
//
//        etName.setText(name);
//        etPhone.setText(phone);
//        etEmail.setText(email);

//        uriString = spFile.getString("img", null);
//        if (!StringUtils.isEmpty(uriString)) {
//            uri = Uri.parse(uriString);
//            Picasso.with(this)
//                    .load(uri)
//                    .transform(new CircleTransform())
//                    .placeholder(R.mipmap.image2)
//                    .error(R.mipmap.image3)
//                    .memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
//                    .config(Bitmap.Config.RGB_565)
//                    .into(ivAvatar);
////            Glide.with(mContext).load(uri).placeholder(R.mipmap.image2).error(R.mipmap.image3).into(ivAvatar);
//        }
    }

    public void ivReturn(View view) {
        finish();
    }

    public void save(View view) {
        UserEntity user = new UserEntity();
        user.setAccount(getStringFromSp("account"));
        user.setNickname(etName.getText().toString());
        user.setPhone(etPhone.getText().toString());
        user.setEmail(etEmail.getText().toString());
        if (uri != null) {
            user.setImg(uri.toString());
        }

        int result = userDao.updateInfo(user);
        if (result == 1) {
            showToast("修改成功！");
        } else {
            showToast("修改失败！");
        }

//        SharedPreferences spFile = getSharedPreferences("user", Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = spFile.edit();
//        editor.putString("name", etName.getText().toString());
//        editor.putString("phone", etPhone.getText().toString());
//        editor.putString("email", etEmail.getText().toString());
//        editor.putString("img", uri.toString());
//        editor.apply();
//        showToast("修改成功！");
    }

    public void addImg(View view) {
        //动态申请权限
        ActivityCompat.requestPermissions(UserActivity.this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);

        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            if (null != data) {
                uri = data.getData();
                ShowPhoto2();
//                img_select = true;可以不选择图片，不选择就是不修改（还是要选择，不然怎么上传（还是可以不用，试了不传参也行））
                //但要判断，可以不用这个判断，path初始为空，没选择就是空，判断path为空就不传参
            }
        }
    }

    private void ShowPhoto2() {
        ContentResolver cr = getContentResolver();
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
            ivAvatar.setImageBitmap(bitmap);
            uri = Uri.parse(uri.toString());
            Picasso.with(this)
                    .load(uri)
                    .transform(new CircleTransform())
                    .placeholder(R.mipmap.logo)
                    .error(R.mipmap.logo)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .config(Bitmap.Config.RGB_565)
                    .into(ivAvatar);
//            Glide.with(mContext).load(uri).placeholder(R.mipmap.image2).error(R.mipmap.image3).into(ivAvatar);
            path = RealPathFromUriUtils.getRealPathFromUri(this, uri);
            System.out.println(path);
        } catch (FileNotFoundException e) {
            Log.e("Exception", e.getMessage(), e);
        }
    }
}